package com.syeet.gulimall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.syeet.common.utils.R;
import com.syeet.gulimall.cart.feign.ProductFeignService;
import com.syeet.gulimall.cart.interceptor.CartInterceptor;
import com.syeet.gulimall.cart.service.CartService;
import com.syeet.gulimall.cart.vo.Cart;
import com.syeet.gulimall.cart.vo.CartItem;
import com.syeet.gulimall.cart.vo.SkuInfoVo;
import com.syeet.gulimall.cart.vo.UserInfoTo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;

/**
 * @author xhl
 * @date 2023/4/25
 */
@Slf4j
@Service
public class CartServiceImpl implements CartService {
    private final String CART_PREFIX = "gulimall:cart:";

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ProductFeignService productFeignService;

    @Resource
    private ThreadPoolTaskExecutor executor;

    /**
     * 添加商品，即购物项到购物车
     *
     * @param skuId
     * @param num
     * @return
     */
    @Override
    public CartItem addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String res = (String) cartOps.get(skuId.toString());
        //商品添加到购物车中

        //购物车原先没有该商品
        if (StringUtils.isEmpty(res)) {
            CartItem cartItem = new CartItem();
            //1.远程查询要添加的商品信息
            CompletableFuture<Void> skuInfoTask = CompletableFuture.runAsync(() -> {
                R r = productFeignService.getSkuInfo(skuId);
                SkuInfoVo skuInfo = r.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                });
                cartItem.setCheck(true);
                cartItem.setCount(num);
                cartItem.setImage(skuInfo.getSkuDefaultImg());
                cartItem.setPrice(skuInfo.getPrice());
                cartItem.setSkuId(skuId);
                cartItem.setTitle(skuInfo.getSkuTitle());

            }, executor);

            //2.远程查询sku的组合信息
            CompletableFuture<Void> skuSaleAttrValueTask = CompletableFuture.runAsync(() -> {
                List<String> list = productFeignService.getSkuSaleAttrValue(skuId);
                cartItem.setSkuAttr(list);
            }, executor);

            CompletableFuture.allOf(skuInfoTask, skuSaleAttrValueTask).get();
            String cartString = JSON.toJSONString(cartItem);
            cartOps.put(skuId.toString(), cartString);

            return cartItem;
        } else {
            //购物车有此商品
            CartItem cartItem = JSON.parseObject(res, CartItem.class);
            cartItem.setCount(cartItem.getCount() + num);
            cartOps.put(skuId.toString(), JSON.toJSONString(cartItem));
            return cartItem;
        }

    }

    @Override
    public CartItem getCartItemBySkuId(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String res = (String) cartOps.get(skuId.toString());
        CartItem cartItem = JSON.parseObject(res, CartItem.class);
        return cartItem;
    }

    @Override
    public Cart getCart() throws Exception {
        Cart cart = new Cart();
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if (userInfoTo.getUserId() != null) {
            //1.登录
            String cartKey = CART_PREFIX + userInfoTo.getUserId();
            //2.如果临时购物车数据还没有合并（合并购物车）
            String tempCartKey = CART_PREFIX + userInfoTo.getUserKey();
            List<CartItem> tempItems = getCartItems(tempCartKey);
            if (tempItems != null && tempItems.size() > 0) {
                //临时购物车有数据，合并到用户购物车中
                for (CartItem tempItem : tempItems) {
                    addToCart(tempItem.getSkuId(), tempItem.getCount());
                }
                //清空临时购物车
                clearCart(tempCartKey);
            }
            //3.获取登录过的购物车数据（包含临时购物车数据）
            List<CartItem> cartItems = getCartItems(cartKey);
            cart.setItems(cartItems);
        } else {
            //2.未登录，获取临时用户购物车数据
            String cartKey = CART_PREFIX + userInfoTo.getUserKey();
            List<CartItem> cartItems = getCartItems(cartKey);
            cart.setItems(cartItems);
        }
        return cart;
    }

    @Override
    public void clearCart(String cartKey) {
        redisTemplate.delete(cartKey);
    }

    @Override
    public void checkItem(Long skuId, Integer check) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        CartItem cartItem = getCartItemBySkuId(skuId);
        cartItem.setCheck(check == 1 ? true : false);
        String res = JSON.toJSONString(cartItem);
        cartOps.put(skuId.toString(), res);
    }

    @Override
    public void changeItem(Long skuId, Integer num) {
        CartItem cartItem = getCartItemBySkuId(skuId);
        cartItem.setCount(num);
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.put(skuId.toString(), JSON.toJSONString(cartItem));

    }

    /**
     * 删除购物项
     *
     * @param skuId
     */
    @Override
    public void deleteItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.delete(skuId.toString());
    }

    @Override
    public List<CartItem> getCurrentUserCartItems() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if (userInfoTo.getUserId() == null) {
            return null;
        } else {
            String cartKey = CART_PREFIX + userInfoTo.getUserId();
            List<CartItem> cartItems = getCartItems(cartKey);
            //获取所有被选中的购物项
            List<CartItem> collect = cartItems.stream()
                    .filter(item -> item.getCheck())
                    .map(item -> {
                        //价格需更新为最新价格
                        R r = productFeignService.getPrice(item.getSkuId());
                        String data = (String) r.get("data");
                        BigDecimal price = new BigDecimal(data);
                        item.setPrice(price);
                        return item;
                    }).collect(Collectors.toList());
            return collect;
        }

    }

    /**
     * 根据key获取购物车购物项
     *
     * @param cartKey
     * @return
     */
    private List<CartItem> getCartItems(String cartKey) {
        BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(cartKey);
        List<Object> objectList = hashOps.values();
        if (objectList != null && objectList.size() > 0) {
            List<CartItem> cartItemList = objectList.stream().map(obj -> {
                String str = (String) obj;
                CartItem cartItem = JSON.parseObject(str, CartItem.class);
                return cartItem;
            }).collect(Collectors.toList());
            return cartItemList;
        }
        return Collections.emptyList();
    }

    /**
     * 获取到要操作的购物车
     *
     * @return
     */
    private BoundHashOperations<String, Object, Object> getCartOps() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        String cartKey = "";
        //操作用户购物车
        if (userInfoTo.getUserId() != null) {
            cartKey = CART_PREFIX + userInfoTo.getUserId();

            //操作临时购物车
        } else {
            cartKey = CART_PREFIX + userInfoTo.getUserKey();
        }
        BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps(cartKey);
        return operations;
    }
}
